package java高并发核心编程.多线程.交替打印;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

//通过原子变量AtomicInteger和闭锁CountDownLatch实现
public class Demo3 {
    private static CountDownLatch countDownLatch = new CountDownLatch(2);
    private static volatile boolean flag = false;
    private static AtomicInteger num = new AtomicInteger(1);
    private static final Integer MAX = 100;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(() -> {
            while (num.get() <= MAX) {
                if (!flag) {
                    System.out.println(Thread.currentThread().getName() + "-->" + num.getAndIncrement());
                    flag = true;
                }
            }
            countDownLatch.countDown();
        }, "奇数线程");

        executorService.submit(() -> {
            while (num.get() <= MAX) {
                if (flag) {
                    System.out.println(Thread.currentThread().getName() + "-->" + num.getAndIncrement());
                    flag = false;
                }
            }
            countDownLatch.countDown();
        });
        countDownLatch.await();
    }
}
